package com.nongcai159.mall.lib_common.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.os.Environment
import com.nongcai159.mall.lib_common.base.BaseApplication
import java.io.*
import java.text.DecimalFormat

/**
 * 文件操作工具类
 *
 *
 * Created by tanbiheng on 2017/9/19.
 */

object FileUtils {
    // 分割线
    val separator = File.separator

    val ROOT_DIR = storagePath!!
    val APK_DIR = ROOT_DIR + "apk${separator}"// app更新包
    val APK_NAME = "Mall.apk"// 更新包文件名
    val CACHE_DIR = ROOT_DIR + "cache${separator}"// 缓存信息
    val CRASH_DIR = ROOT_DIR + "crash${separator}"// 崩溃日志
    val HEAD_DIR = ROOT_DIR + "head${separator}"// 头像
    val IMAGE_DIR = ROOT_DIR + "image${separator}"// 图片


    private val DIRS = arrayOf(ROOT_DIR, APK_DIR, CACHE_DIR, CRASH_DIR, HEAD_DIR, IMAGE_DIR)
    private val cacheDir = arrayOf(APK_DIR, CACHE_DIR, CRASH_DIR, HEAD_DIR, IMAGE_DIR)

    /**
     * 获取缓存文件的大小
     *
     * @return
     */
    val cacheSize: String
        get() {
            var size = 0.0
            for (i in cacheDir.indices) {
                val file = File(cacheDir[i])
                size += getDirSize(file)
            }

            val df = DecimalFormat("#.##")

            return df.format(size) + "M"
        }

    /**
     * 得到SDCard的路径
     *
     * @return
     */
    val storagePath: String?
        get() {
            var filePath: File? = BaseApplication.INSTANCE!!.getExternalFilesDir(null)

            return if (filePath != null) {
                filePath.absolutePath + separator
            } else {
                null
            }
        }

    /**
     * 创建文件
     *
     * @param path
     * @return
     */
    fun createFile(path: String?): File? {
        if (path == null) {
            return null
        }
        val file = File(path)
        if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
                return null
            }

        }

        return file
    }

    /**
     * 在Android/data/下创建目录
     *
     * @param dirName
     * @return
     */
    fun createDataDir(dirName: String) {
        val file = File(dirName)
        if (!file.exists()) {
            val state = file.mkdir()
            MLog.d(dirName + "文件夹创建状态 : " + state)
        }
    }

    /**
     * 创建项目文件目录
     * 无需申请权限
     */
    fun createAppDir() {
        for (i in DIRS.indices) {
            val dir = DIRS[i]
            createDataDir(dir)
        }
    }

    /**
     * 获取文件夹大小
     *
     * @param file
     * @return
     */
    fun getDirSize(file: File): Double {
        if (file.exists()) {
            //如果是目录则递归计算其内容的总大小
            if (file.isDirectory) {
                val childList = file.listFiles()
                var size = 0.0
                for (f in childList) {
                    size += getDirSize(f)
                }
                return size
            } else {
                //如果是文件则直接返回其大小,以“兆”为单位
                return file.length().toDouble() / 1024.0 / 1024.0
            }
        }

        return 0.0
    }

    /**
     * 清除缓存
     * 需要在线程中执行
     */
    fun clearCache() {
        for (i in cacheDir.indices) {
            delCacheFile(cacheDir[i])
        }

        ImageLoader.clearDiskCache()
    }

    /**
     * 删除缓存文件
     *
     * @param path
     */
    private fun delCacheFile(path: String) {
        try {
            val file = File(path)
            if (file == null || !file.exists()) {
                return
            }

            if (file.isFile) {
                file.delete()
            } else {
                val fileList = file.listFiles()
                if (fileList == null || fileList.size <= 0) {
                    return
                }

                val listSize = fileList.size
                for (i in 0 until listSize) {
                    val childFile = fileList[i]

                    if (childFile.isFile) {
                        childFile.delete()
                    } else {
                        delCacheFile(childFile.absolutePath)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 保存bitmap
     *
     * @param bitmap
     * @param path
     * @return
     */
    fun saveBitmap2File(bitmap: Bitmap, path: String): Boolean {
        val format = CompressFormat.PNG
        val quality = 100
        var stream: OutputStream? = null
        try {
            stream = FileOutputStream(path)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        return bitmap.compress(format, quality, stream)
    }

    /**
     * 判断SD卡上的文件是否存在
     *
     * @param filePath
     * @return
     */
    fun isFileExist(filePath: String?): Boolean {
        if (filePath == null) {
            return false
        }

        val file = File(filePath)
        return file.exists()
    }


    fun readAssetsFileToString(context: Context, name: String): String {
        val result = StringBuilder()
        var temp: String
        var inputStream: InputStream? = null
        var bufferedReader: BufferedReader? = null
        try {
            inputStream = context.assets.open(name)
            bufferedReader = BufferedReader(InputStreamReader(inputStream!!, "UTF-8"))
            while (bufferedReader != null) {
                temp = bufferedReader.readLine()
                if (temp != null) {
                    result.append(temp)
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close()
                    inputStream = null
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }

            if (bufferedReader != null) {
                try {
                    bufferedReader.close()
                    bufferedReader = null
                } catch (e: IOException) {
                    e.printStackTrace()
                }

            }
        }
        return result.toString()
    }
}